package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author: hea7en
 * @Date: 2024/5/13 5:53 PM
 * @Description: 菜品管理接口实现类
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    FlavorMapper flavorMapper;

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 添加菜品和对应口味
     * @param dishDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addDishAndFlavor(DishDTO dishDTO) {
        // 向菜品表插入数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.saveDish(dish);

        // 获取到save方法自动生成的主键值，xml里的useGeneratedKeys="true"，会自动将主键值赋值给dish对象
        Long dishId = dish.getId();

        // 向口味表插入数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null && flavors.size() >0) {
            // 赋值菜品id
            flavors.forEach(flavor ->{
                flavor.setDishId(dishId);
            });
            flavorMapper.saveBatch(flavors);
        }

        // 删除掉所有缓存
        clearCache("dish:*");
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO pageQueryDTO) {
        // 开启分页查询
        int pageNum = pageQueryDTO.getPage();
        int pageSize = pageQueryDTO.getPageSize();
        PageHelper.startPage(pageNum, pageSize);

        // 执行自定义查询
        Page<DishVO> page = dishMapper.pageQuery(pageQueryDTO);
        long total = page.getTotal();
        List<DishVO> results = page.getResult();

        return new PageResult(total, results);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDish(List<Long> ids) {
       // 校验是否是启售状态
        List<Dish> dishList =  dishMapper.getDishByIds(ids);
        dishList.forEach(dish ->{
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

       // 校验是否跟套餐表有关联数据
        List<SetmealDish> setmealDish = setmealDishMapper.getSetmealByDishIds(ids);
        if (setmealDish != null && setmealDish.size()>0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 删除菜品表数据
        dishMapper.deleteBatch(ids);

        // 删除口味表数据
        flavorMapper.deleteByDishIds(ids);

        // 删除掉所有缓存
        clearCache("dish:*");
    }

    @Override
    public void startOrStop(int status, Long id) {
       dishMapper.startOrStop(status, id);

        // 删除掉所有缓存
        clearCache("dish:*");
    }

    @Override
    public DishVO getDishById(Long id) {
        // 获取菜品数据
        Dish dish = dishMapper.getById(id);

        // 获取口味数据
        List<DishFlavor> flavors = flavorMapper.getByDishId(id);

        // 组装数据
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    @Override
    public void editDishAndFlavor(DishDTO dishDTO) {
        // 修改菜品表数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        // 先删除口味表数据
        flavorMapper.deleteByDishIds(Arrays.asList(dishDTO.getId()));

        // 添加口味表数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null && flavors.size() >0) {
            // 赋值菜品id
            flavors.forEach(flavor ->{
                flavor.setDishId(dishDTO.getId());
            });
            flavorMapper.saveBatch(flavors);
        }

        // 删除掉指定缓存
        clearCache("dish:"+dish.getCategoryId());
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        // redis的key
        String redisKey = "dish:" + dish.getCategoryId();

        // 先查询redis缓存是否有数据
        List<DishVO> dishRedisList = (List<DishVO>) redisTemplate.opsForValue().get(redisKey);
        if (dishRedisList!=null && dishRedisList.size()>0) {
            return dishRedisList;
        }

        // 没有缓存则查数据库
        List<DishVO> dishVOList = new ArrayList<>();
        List<Dish> dishList = dishMapper.list(dish);
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        // 将数据存入redis
        redisTemplate.opsForValue().set(redisKey, dishVOList);

        return dishVOList;
    }

    @Override
    public List<DishVO> getListByCategoryId(Long categoryId) {
        // 根据分类id查出所有菜品
        Dish dish = Dish.builder().categoryId(categoryId).build();
        List<Dish> dishs = dishMapper.list(dish);

        // 将菜品数据封装成dishVO
        List<DishVO> dishList = new ArrayList<>();
        dishs.forEach(d ->{
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            dishList.add(dishVO);
        });
        return dishList;
    }

    /**
     * 清理redis缓存
     * @param pattern
     */
    private void clearCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
